import React, { useEffect } from 'react';
import { iframeMicroConfig } from './config';
import { ifrmaPostMessageFnify } from '@/utils/iframe';

type IframeMicroProps = {
 path: string;
 microApp: string;
 activate: boolean;
};

const style100 = {
    width: '100%',
    height: '100%',
};

const iframeCacheMap: {
    [key: string]: {
        ele: HTMLIFrameElement;
        divUUID: string;
        path: string;
    };
} = {};

// const iframeCountCacheMap: {
//     [key: string]:number;
// } = {};

const iframeGotoPage = ifrmaPostMessageFnify({
 fn: 'gotoPage',
});

export const remoteCallFunction = async ({
    microApp,
    functionName,
    args,
}: {
    microApp: string;
    functionName: string;
    args: any[];
}) => {

    let iframeState = iframeCacheMap[microApp];

    if(!iframeState) {
        throw new Error(`您当前没有打开任何一个 微前端(id = ${microApp} )的页面`);
    }

    const func = ifrmaPostMessageFnify({
        fn: functionName,
    });

    return func(iframeState.ele, ...args);
};

const useIframeElement = ({
    path,
    microApp,
    divUUID,
    coverEle,
    activate,
}: {
    path: string;
    microApp: string; 
    divUUID: string;
    coverEle: HTMLDivElement | null;
    activate: boolean;
}) => {

    useEffect(() => {
        
        if(!coverEle) {
            return;
        }

        let iframeState = iframeCacheMap[microApp];

        if(!iframeState) {
            const configObj = iframeMicroConfig.apps.find(item => item.name == microApp);

            if(!configObj) {
                return;
            }
            const newIframe = document.createElement('iframe');
            newIframe.setAttribute('name', `iframe_micro_${microApp}`);
            newIframe.setAttribute('style', 'display: none');
            newIframe.src = `${configObj.entry}${path}`;
        
            document.body.appendChild(newIframe);
        
            iframeCacheMap[microApp] = {
                ele: newIframe,
                path,
                // divUUID,
            } as any;
        
            iframeState = iframeCacheMap[microApp];
        } else {
        }

        if (activate) {
            // console.log('进入可视区域');
            if(iframeState.divUUID !== divUUID) {
                iframeState.divUUID = divUUID;
            }

            if(iframeState.ele.style.display === "none") {
                const { left, top, height, width} = coverEle.getBoundingClientRect();
                iframeState.ele.setAttribute('style', `position: fixed; left: ${left}px; top: ${top}px; height: ${ height !==0 ? `${height}px`: 'auto' }; width: ${width}px`);
            }

            if(iframeState.path !== path) {
                iframeState.path = path;
                iframeGotoPage(iframeState.ele, path).then(
                    () => {}, 
                    (e) => {
                        console.error(e)
                    }
                );
            }

        } else {
            // console.log('移出可视区域');
            if(iframeState.divUUID === divUUID) {
                iframeState.ele.setAttribute('style', `display: none`);
            }
        }

        // const observer = new IntersectionObserver(entries => {
        //     if (entries[0].intersectionRatio > 0) {
        //         // console.log('进入可视区域');
        //         if(iframeState.divUUID !== divUUID) {
        //             const { left, top, height, width} = coverEle.getBoundingClientRect();
        //             iframeState.ele.setAttribute('style', `position: fixed; left: ${left}px; top: ${top}px; height: ${ height !==0 ? `${height}px`: 'auto' }; width: ${width}px`);
        //             iframeState.divUUID = divUUID;
        //         }
        //     } else {
        //         // console.log('移出可视区域');
        //         if(iframeState.divUUID === divUUID) {
        //             iframeState.ele.setAttribute('style', `display: none`);
        //         }
        //     }
        // });

        // observer.observe(coverEle);

        // return (() => {
        //     observer.disconnect();
        // });

        return (() => {
            // 页面关闭时隐藏
            if(iframeState.divUUID === divUUID) {
                iframeState.ele.setAttribute('style', `display: none`);
            }
        });

    }, [coverEle, path]);

    /**
     * 当所以页面的 div 销毁时， iframe 也消耗
     */
    // useEffect(() => {
    //     if(iframeCountCacheMap[microApp] === undefined) {
    //         iframeCountCacheMap[microApp] = 0;
    //     };
    //     iframeCountCacheMap[microApp] ++;
    //     return () => {
    //         iframeCountCacheMap[microApp] --;
    //         if(iframeCountCacheMap[microApp] === 0) {
    //             const iframeState = iframeCacheMap[microApp];
    //             iframeState.ele.remove();
    //             delete iframeCacheMap[microApp];
    //         }
    //     };
    // }, []);

};

export const IframeMicro = ({
    path,
    microApp,
    activate,
    ...props
}: IframeMicroProps) => {

    const [coverEle, setCoverEle] = React.useState<HTMLDivElement | null>(null);

    const divUUID = React.useMemo(() => `iframe_${Math.random().toString(16).slice(2)}`, []);

    useIframeElement({ path, microApp, divUUID, coverEle, activate });

    return (<div style={style100} {...props} ref={setCoverEle}></div>);
};
